<?php
class CatalogCategory extends CActiveRecord
{
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    public function tableName()
    {
        return 'CatalogCategory';
    }

    public function rules()
    {
        return array(
                array('title, m_k, m_d, description, url, l_id', 'required'),
                array('lang_parent_id, l_id, parent_id', 'numerical', 'integerOnly'=>true),
                array('title, url', 'length', 'max'=>255),
                array('image', 'length', 'max'=>50),
                array('lang_parent_id, id, title, m_k, m_d, description, image, url, l_id, parent_id', 'safe', 'on'=>'search'),
            );
    }

    public function relations()
    {
        return array(
                'catalogs'  => array(self::HAS_MANY, 'Catalog', 'catalog_category_id'),
                'l'         => array(self::BELONGS_TO, 'Language', 'l_id'),
            );
    }

    public function attributeLabels()
    {
        return array(
                'id'             => Yii::t('system','ID'),
                'title'          => Yii::t('system','Title'),
                'm_k'            => Yii::t('system','M K'),
                'm_d'            => Yii::t('system','M D'),
                'description'    => Yii::t('system','Description'),
                'image'          => Yii::t('system','Image'),
                'url'            => Yii::t('system','Url'),
                'l_id'           => Yii::t('system','L'),
                'parent_id'      => Yii::t('system','Parent'),
                'lang_parent_id' => Yii::t('system','lang_parent_id'),
        );
    }
    
    //Результат переведенные и не переведенные категории
    public static function getCategoryTranslations($id,$parent_id){
        //Выборка
        $command=Yii::app()->db->createCommand()
            ->select('c.id as category_id, c.title, l.name, l.id as language_id')
            ->from('CatalogCategory c')
            ->join('Language l', 'c.l_id = l.id')
            ->where('c.lang_parent_id = :id',array(':id'=>$id))
            ->queryAll();
        
        //Количество языков. От минусовываем дефолтовый язык
        $count_language = Language::countLang()-1;
        //Имеющиеся переводы
        $language_for_item = Array();
        
        //То на что есть перевод
        if (count($command)>0){
            foreach ($command as $key => $value) {
                $language_for_item[] = $value['language_id'];
                $view .= CHtml::link($value['name'].' - '.$value['title'],array('/catalog/CatalogCategory/update','id'=>$value['page_id'])).'<br>';
            }
        }
        //Остальое без перевода
        if ($count_language > count($command)){
            foreach (Language::allExcept($language_for_item) as $value) {
                $view .= CHtml::link($value['name'].' - Нет перевода',array('/catalog/CatalogCategory/create','language_id'=>$value['id'],'lang_parent_id'=>$id,'parent_id'=>$parent_id),array('class'=>'warning')).'<br>';
            }
        }
        return $view;
    }
    

    //Возвращает Заголовок по ID
    public static function getTitleOnId($id){
        $command=Yii::app()->db->createCommand()
            ->select('title')
            ->from('CatalogCategory')
            ->where('id = :id',array(':id'=>$id))
            ->queryScalar();
        return $command;
    }

    //Подготавливает массив для drop down
    public static function dropDownItemsAll(){
        $items= Array();
        $model = self::model()->findAll('l_id = :language_id', array(':language_id'=>Language::getIdForLang(Yii::app()->params['dafaultLanguage'])));
        $items[0] = ' -- ';
        foreach ($model as $value) {
            $items[$value->id] = $value->title;
        }
        return $items;
    }
        
    //Все категории имеющие перевод текущего языка
    public static function getAllCategoryCurrentLanguage(){
        $dataReader=Yii::app()->db->createCommand()
            ->select('*')
            ->from('CatalogCategory')
            ->where('l_id=:language',array(':language' => Language::getId()))
            ->queryAll();
        return $dataReader;
    }
    
    public static function getCategoryByUrl($url){
        //Выборка
        $command=Yii::app()->db->createCommand()
        ->select('c_c.title, c_c.m_k, c_c.m_d, c_c.id')
        ->from('CatalogCategory c_c')
        ->where('c_c.l_id = :language AND c_c.url = :url',
                array(
                    ':language' => Language::getId(),
                    ':url'=>$url,
                ))
        ->queryRow();
        return $command;
    }
        
   
    
    //Все категории имеющие перевод текущего языка
    public static function getAllCategory(){
        $dataReader=Yii::app()->db->createCommand()
            ->select('*')
            ->from('CatalogCategory')
            ->queryAll();
        return $dataReader;
    }

    public function search()
    {	
        $criteria=new CDbCriteria;
        $criteria->compare('id',$this->id);
        $criteria->compare('title',$this->title,true);
        $criteria->compare('m_k',$this->m_k,true);
        $criteria->compare('m_d',$this->m_d,true);
        $criteria->compare('description',$this->description,true);
        $criteria->compare('image',$this->image,true);
        $criteria->compare('url',$this->url,true);
        $criteria->compare('l_id',$this->l_id);
        $criteria->compare('parent_id',$this->parent_id);
        $criteria->compare('l_id',Language::getIdForLang(Yii::app()->params['dafaultLanguage']));
        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
            'sort'=>array(
                        'defaultOrder'=>'id, parent_id',
                ),
        ));
    }
    
    //Удаляем дерево категорий
    public function beforeDelete()
    {
        $tree = new IdCategoryTree();
        $tree = $tree->getIdTreeCategory($this->id);
        if (count($tree) > 0)
        {
            $command = Yii::app()->db->createCommand();
            $command->delete('CatalogCategory', array('in', 'id', $tree));
            $command->delete('CatalogCategory', 'lang_parent_id=:id',array(':id'=>$this->id));
        }
        return parent::beforeDelete();
    }
    
}